package front

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	category2 "supervideo/app/models/category"
	"supervideo/app/models/video"
	"supervideo/app/models/video_category_map"
	"supervideo/app/models/zone"
	"supervideo/pkg/database"
)

type ListController struct {
}

func (list ListController) Index(c *gin.Context) {

	// 从路由函数中获取的分类参数
	zoneId, _ := strconv.Atoi(c.Param("zone_id"))
	categoryId, _ := strconv.Atoi(c.Query("cat"))
	addressId, _ := strconv.Atoi(c.Query("addr"))
	sortId, _ := strconv.Atoi(c.Query("so"))

	// 搜索区间
	var zones []zone.Zone
	database.DB.Order("sort desc").Find(&zones)

	//获取类型
	var categories []category2.Category
	database.DB.Order("sort desc").Find(&categories)

	var categoryItems []category2.Category
	var addressItems []category2.Category

	// 1. 类型,   地区
	for _, category := range categories {
		if category.ParentID == 1 {
			categoryItems = append(categoryItems, category)
		}
		if category.ParentID == 37 {
			addressItems = append(addressItems, category)
		}
	}

	type SortLink struct {
		Index int
		Title string
	}

	sortLinks := []SortLink{
		{Index: 0, Title: "按时间"},
		{Index: 1, Title: "按人气"},
		{Index: 2, Title: "按评分"},
	}

	// 搜索视频表
	query := database.DB.Model(&video.Video{}).Where("zone_id = ?", zoneId).Where("status = ?", 1)
	if categoryId != 0 {
		var ids []string
		database.DB.Model(video_category_map.VideoCategoryMap{}).Where("category_id", categoryId).Pluck("video_id", &ids)
		query = query.Where("id in ?", ids)
	}
	if addressId != 0 {
		query = query.Where("address_id = ?", addressId)
	}
	if sortId == 1 {
		query = query.Order("created_at desc")
	}
	if sortId == 2 {
		query = query.Order("sort desc")
	}
	if sortId == 3 {
		query = query.Order("grade desc")
	}

	videos, paging := video.Paginate(c, 20, query)

	// 判断是不是有下一页

	c.HTML(http.StatusOK, "list.html", gin.H{
		"Title":         "123",
		"zones":         zones,
		"zoneId":        zoneId,
		"sortId":        sortId,
		"categoryItems": categoryItems,
		"addressItems":  addressItems,
		"categoryId":    categoryId,
		"addressId":     addressId,
		"sortLinks":     sortLinks,
		"videos":        videos,
		"paging":        paging,
	})

}
